package com.lac.component.rabbitmq.dead;

import org.springframework.context.annotation.Configuration;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;

/**
 * 延迟交换器和队列
 */
@Configuration
public class DelayedConfig {
    public static final String DELAYED_EXCHANGE_NAME = "my.delayed.exchange";
    public static final String DELAYED_QUEUE_NAME = "delayed.queue";
    public static final String DELAYED_ROUTING_KEY = "delayed.routing.key";

    @Bean
    public CustomExchange delayedExchange() {
        Map<String, Object> args = new HashMap<>();
        // 确保 "x-delayed-type" 的值是以下之一： "direct", "topic", "fanout", "headers"
        // 你的错误信息是 PRECONDITION_FAILED - Invalid argument, 'x-delayed-type' must be an existing exchange type
        // 这说明这里的类型有问题。
        args.put("x-delayed-type", "direct"); // 或者 "topic", "fanout", "headers"

        // CustomExchange(name, type, durable, autoDelete, arguments)
        // type 必须是 "x-delayed-message"
        return new CustomExchange(DELAYED_EXCHANGE_NAME, "x-delayed-message", true, false, args);
    }

    @Bean
    public Queue delayedQueue() {
        return new Queue(DELAYED_QUEUE_NAME, true); // durable: true
    }

    @Bean
    public Binding delayedBinding(Queue delayedQueue, CustomExchange delayedExchange) {
        // 如果你的延迟交换机类型是 direct，那么这里应该使用 with(routingKey)
        return BindingBuilder.bind(delayedQueue).to(delayedExchange).with(DELAYED_ROUTING_KEY).noargs();
    }

    // 依然需要监听器
    // @RabbitListener(queues = DELAYED_QUEUE_NAME)
    // public void receiveDelayedMessages(String message) {
    //     System.out.println("RECEIVED DELAYED MESSAGE: " + message);
    // }
}